package visiopuce.service.document;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.encoders.EncoderUtil;
import org.jfree.chart.encoders.ImageFormat;

import visiopuce.ApplicationContexte;
import visiopuce.objets.Alteration;
import visiopuce.objets.Analyse;
import visiopuce.objets.GeneNcbi;
import visiopuce.objets.Personne;
import visiopuce.objets.Prelevement;
import visiopuce.objets.Puce;
import visiopuce.service.AnalyseServiceImpl;
import visiopuce.service.PersonneServiceImpl;
import visiopuce.service.PrelevementServiceImpl;
import visiopuce.service.PuceServiceImpl;
import visiopuce.service.ReferentielServiceImpl;
import visiopuce.ui.view.CNVTabItem;
import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.images.FileImageProvider;
import fr.opensagres.xdocreport.document.images.IImageProvider;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;

public class AlterationDoc {

	public String createDocument(Alteration cnv, CNVTabItem cnvTabItem) {
		String nomFichierout = "";
		try {

			boolean creer = true;
			InputStream in = new FileInputStream(new File(ApplicationContexte.REPERTOIRE_MODEL + "cnvDoc.docx"));
			IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
			Puce p = PuceServiceImpl.getInstance().getPuceByid(cnv.getPuce().getIdPuce());
			Analyse analyse = AnalyseServiceImpl.getInstance().getAnalyseByIdAnalyse(p.getAnalyse().getIdAnalyse());
			Prelevement prelevement = PrelevementServiceImpl.getInstance().getPrelevementById(analyse.getPrelevement().getIdPrelevement());
			Personne personne = PersonneServiceImpl.getInstance().getPersonneById(prelevement.getPersonne().getIdPersonne());
			Date d = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("dd_MM_yyyy");
			SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
			cnv.setSondeDebut(cnv.getSondeDebut().trim());
			cnv.setSondeFin(cnv.getSondeFin().trim());
			IContext context = report.createContext();
			context.put("personne", personne);
			context.put("dateNaissance", formatter.format(personne.getDateNaissance()));
			context.put("prelevement", prelevement);
			context.put("taille", (cnv.getFinHg19() - cnv.getDebutHg19()) / 1000);
			context.put("cnv", cnv);
			List<GeneNcbi> genes = ReferentielServiceImpl.getInstance().getGeneNCBIByBorne(cnv, 0);
			for (GeneNcbi geneNcbi : genes) {
				if (geneNcbi.getDisorderMimname() == null){
					geneNcbi.setDisorderMimname("");
				}
				if (geneNcbi.getMimnb() == null){
					geneNcbi.setMimnb(0);
				}	
			}
			context.put("genes", genes);
			FieldsMetadata metadata = new FieldsMetadata();
			metadata.addFieldAsImage("graphe");
			report.setFieldsMetadata(metadata);

			File fileImageOut = new File(ApplicationContexte.REPERTOIRE_DOCUMENT + prelevement.getNumeroPrelevement() + "_" + personne.getNom() + "_" + personne.getPrenom() + "_cnv_Chr" + cnv.getChromosome() + "_" + cnv.getDebutHg19() + "-" + cnv.getFinHg19() + "_" + sdf.format(d) + ".png");
			OutputStream outImage = new BufferedOutputStream(new FileOutputStream(fileImageOut));

			JFreeChart chart = cnvTabItem.getGraph().getjFreeChart();
			BufferedImage bufferedImage = chart.createBufferedImage(750, 500, null);
			EncoderUtil.writeBufferedImage(bufferedImage, ImageFormat.PNG, outImage);

		
			IImageProvider graph = new FileImageProvider(fileImageOut, true);

			context.put("graphe", graph);

			File fileout = new File(ApplicationContexte.REPERTOIRE_DOCUMENT + prelevement.getNumeroPrelevement() + "_" + personne.getNom() + "_" + personne.getPrenom() + "_cnv_Chr" + cnv.getChromosome() + "_" + cnv.getDebutHg19() + "-" + cnv.getFinHg19() + "_" + sdf.format(d) + ".docx");
			if (fileout.exists()) {
				creer = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Fichier existant", "Le fichier " + fileout.getName() + " existe déjà souhaitez vous l'écraser?");
			}
			if (creer) {

				OutputStream out = new FileOutputStream(fileout);
				report.process(context, out);
				if (fileout.exists()) {
					nomFichierout += fileout.getName();
				}
			}
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XDocReportException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return nomFichierout;
	}

}
